﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Calcite.Classes;
using System.IO;
using LumenWorks.Framework.IO.Csv;
using Calcite.Dialogs;
using Calcite.Properties;

namespace Calcite
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();


        }

        private void Main_Load(object sender, EventArgs e)
        {
            // Load up a worksheet
            Form dataWindow = new Worksheet();
            dataWindow.MdiParent = this;
            dataWindow.Show();
            // Set size to be as user last left it
            this.Width = UserSettings.Default.MainWindowSize.Width;
            this.Height = UserSettings.Default.MainWindowSize.Height;
        }

        internal void ImportDataToWorksheet()
        {
            // TODO: Implement import code
            this.chooseImportDataFileDialog.ShowDialog();
            //Console.WriteLine("{0}", Calcite.Classes.Misc.Functions.GetMimeFromFile(importDataFileDialog.FileName));
            ImportFileDialog importFileDialog = new ImportFileDialog(this.chooseImportDataFileDialog.FileNames);
            importFileDialog.ShowDialog();
            foreach (string fileName in importFileDialog.FileNames) 
            {
                try
                {
                    using (TextReader fileReader = new StreamReader(fileName))
                    {
                        bool hasHeaders = false;
                        bool trimSpaces = true;
                        using (CsvReader csvReader = new CsvReader(fileReader,
                            hasHeaders, importFileDialog.Delimiter[0], importFileDialog.QuoteString[0],
                            importFileDialog.EscapeString[0], importFileDialog.CommentString[0], trimSpaces))
                        {
                            //Form dataWindow = new Worksheet();
                            //dataWindow.MdiParent = this;
                            //// Have to show before populating the data so that the DataTable is bound and filled
                            //dataWindow.Show();
                            //if (importFileDialog.Headers.Count != 0)
                            //{

                            //}
                            
                        }
                    }
                }
                catch (IOException e) 
                {
                    // TODO: Put in good dialog
                    Console.WriteLine("Can't open file: {0}", e.Message);
                } 
            }
            // Always Be Closing
            this.chooseImportDataFileDialog.Dispose();
            importFileDialog.Dispose();
        }

        private void worksheetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form dataWindow = new Worksheet();
            dataWindow.MdiParent = this;
            dataWindow.Show();
        }

        private void closeWindowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form formWithFocus = this.ActiveMdiChild;
            // TODO: Implement save before close
            if (formWithFocus != null)
            {
                formWithFocus.Close();
                formWithFocus.Dispose();
            }
        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ImportDataToWorksheet();
        }

        protected override bool ProcessDialogKey(Keys keyData)
        // Handle key pushes in the grid window
        {
            // TODO: entering numbers starts editing in child
            Form formWithFocus = this.ActiveMdiChild;
            switch (keyData)
            {
                // TODO: Get rid of this!
                case Keys.Control | Keys.T:
                    DebugCode();
                    break;
            }

            return base.ProcessDialogKey(keyData);
        }

        private void overwriteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form formWithFocus = this.ActiveMdiChild;
            if (formWithFocus is Worksheet)
            {
                Worksheet frm = (Worksheet)formWithFocus;
                if (frm.ActiveWorksheetGridView != null)
                {
                    frm.ActiveWorksheetGridView.PasteToCells("overwrite");
                }
            }
        }

        private void addNewRowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form formWithFocus = this.ActiveMdiChild;
            if (formWithFocus is Worksheet)
            {
                Worksheet frm = (Worksheet)formWithFocus;
                if (frm.ActiveWorksheetGridView != null)
                {
                    frm.ActiveWorksheetGridView.PasteToCells("insertrows");
                }
            }
        }

        private void addNewColumnsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form formWithFocus = this.ActiveMdiChild;
            if (formWithFocus is Worksheet)
            {
                Worksheet frm = (Worksheet)formWithFocus;
                if (frm.ActiveWorksheetGridView != null)
                {
                    frm.ActiveWorksheetGridView.PasteToCells("insertcols");
                }
            }
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Code to copy data from child form

            Form formWithFocus = this.ActiveMdiChild;
            if (formWithFocus is Worksheet)
            {
                Worksheet frm = (Worksheet)formWithFocus;
                if (frm.ActiveWorksheetGridView != null)
                {
                    frm.ActiveWorksheetGridView.Copy();
                }
            }
            else
            {
                // Other sort of object
            }
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Quit application
            // TODO: Include code to save before exit
            if (MessageBox.Show("Are you sure you want to exit?", "My Application",
      MessageBoxButtons.YesNo, MessageBoxIcon.Question)
      == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void DebugCode()
        // TODO: remove this method!
        {
            Console.WriteLine("Debug code:");
            Form formWithFocus = this.ActiveMdiChild;
            if (formWithFocus is Worksheet)
            {
                Worksheet frm = (Worksheet)formWithFocus;
                Console.WriteLine("Cell: {0}", frm.rawDataGridView.Rows[0].Cells[0].Value);
                //Console.WriteLine("Cols: {0}, Rows {1}",
                //    frm.rawDataGridView.data.Columns.Count.ToString(),
                //    frm.rawDataGridView.data.Rows.Count.ToString());
            }
            StringReader stringReader = new StringReader("1.32, 1.11e4, 1.2\n1.1, 1.2, 3");
            CalciteCsv.CsvReader reader = new CalciteCsv.CsvReader(stringReader, new CalciteCsv.CsvSpec(CalciteCsv.CsvTypes.CommaSeperatedFile));
            reader.ReadNextRow();
            Console.WriteLine("{0} and {1}", reader.Columns[0], reader.Columns[1]);
            reader.ReadNextRow();
            Console.WriteLine("{0} and {1}", reader.ColumnsAsDoubles[0], reader.ColumnsAsDoubles[1]);

        }

        private void editColumnsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild is Worksheet)
            {
                Worksheet ws = (Worksheet)this.ActiveMdiChild;
                if (ws.ActiveWorksheetGridView != null)
                {
                    ws.ActiveWorksheetGridView.EditColumns();
                }
            }
            
        }

        private void insertColumnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild is Worksheet)
            {
                Worksheet ws = (Worksheet)this.ActiveMdiChild;
                if (ws.ActiveWorksheetGridView != null)
                {
                    ws.ActiveWorksheetGridView.InsertColumnAtSelection();
                }
            } 
        }

        private void insertRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild is Worksheet)
            {
                Worksheet ws = (Worksheet)this.ActiveMdiChild;
                if (ws.ActiveWorksheetGridView != null)
                {
                    ws.ActiveWorksheetGridView.InsertRowAtSelection();
                }
            } 
        }

        private void Main_Resize(object sender, EventArgs e)
        {
            // Persist preferences
            UserSettings.Default.MainWindowSize = new System.Drawing.Size(this.Width, this.Height);
            UserSettings.Default.Save();
        }

    }
}
